﻿
function addRow(tblID) {
    $('#' + tblID + ' tbody>tr:last').clone(true).insertAfter('#' + tblID + ' tbody>tr:last');
    $('#' + tblID + ' tbody>tr:last').each(function () { $(this).find('input[type=text], textarea').val('') });

    var rows = $('#' + tblID).find('tr');
    var newRow = rows[rows.length - 1];
    var closeBtn = $(newRow).find('button');
    $(closeBtn).show();
    $(closeBtn).parent().css('vertical-align','top');
    
    return false;
}

function removeRow(btn) {
    var tbl = $(btn).parent().parent().parent();
    var rowCount = $(tbl).find('tr').length;

    if (rowCount > 2) {
        $(btn).parent().parent().remove();
        if (rowCount == 3)
        {
            var preRow = $(tbl).find('tr')[1];
            var closeBtn = $(preRow).find('button');
            $(closeBtn).hide();
        }
    }
    else {
        alert('Last row can not be removed.');
    }
    return false;
}

$(document).ready(function () {
    $('input[Validate =PO]').blur(function () { validatePO(this); });
    $('input[Validate =Decimal]').on("keypress keyup blur", function (event) { validateDecimal(this); });
    $('input[Validate =Number]').on("keypress keyup blur", function (event) { validateNumber(this); });
});

function validateDecimal(txt) {
    $(txt).val($(txt).val().replace(/[^0-9\.]/g, ''));
    if ((event.which != 46 || $(txt).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
}

function validateNumber(txt) {
    $(txt).val($(txt).val().replace(/[^\d].+/, ""));
    if ((event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
}


function validatePO(txt) {
    if (txt.value == '')
        return;
    $.ajax({
        type: "POST",
        url: "http://" + window.location.host + "/Inventory/Services/Services.aspx/IsValidPO",
    data: "{'po': '" + txt.value + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        if (msg.d == false) {
            alert('Invalid PO Number!!!');
            //<%= "$(txt).focus();" %>
        }

    }
});
}


function executeScalar(txt, serviceMethod, outputControlID) {
    if (txt.value == '')
        return;
    $.ajax({
        type: "POST",
        url: "http://" + window.location.host + "/Inventory/Services/Services.aspx/" + serviceMethod,
        data: "{'input': '" + txt.value + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msg.d.length > 0) {
                $('#' + outputControlID).val(msg.d);
                //<%= "$(txt).focus();" %>
            }

        },
        error: function (ts) {
            alert(ts.responseText);
        }
    });
}


function getValues(tblID, fields, inputs)
{
    var json = "[";
    var data = [];
    var tbl = $('#' + tblID);
    var rows = $(tbl).find('tr');

    for (var j = 1; j <= rows.length-1; j++) {
        var row=rows[j];
        var obj = {};
        json += "{";
        for (var i = 0; i <= inputs.length - 1; i++) {
            obj['"' + fields[i] + '"'] = $(row).find('#' + inputs[i]).val();
            if(i==inputs.length-1)
                json += '"' + fields[i] + '":"' + $(row).find('#' + inputs[i]).val() + '"';
            else
                json += '"' + fields[i] + '":"' + $(row).find('#' + inputs[i]).val() + '",';
        }
        if (j == rows.length - 1)
            json += "}";
        else
            json += "},";

        data.push(obj);
    }
    json += "]";
    return json;
}

//If parameter is List<asf> then Json should start from [ else {
function getValuesForEdit(tblID, fields, inputs, editID, editID_DBFieldName) {
    var json = "[";
    var data = [];
    var tbl = $('#' + tblID);
    var rows = $(tbl).find('tr');

    for (var j = 1; j <= rows.length - 1; j++) {
        var row = rows[j];
        var obj = {};
        json += "{";
        json += '"' + editID_DBFieldName + '":"' + editID + '",';
        for (var i = 0; i <= inputs.length - 1; i++) {
            obj['"' + fields[i] + '"'] = $(row).find('#' + inputs[i]).val();
            if (i == inputs.length - 1)
                json += '"' + fields[i] + '":"' + $(row).find('#' + inputs[i]).val() + '"';
            else
                json += '"' + fields[i] + '":"' + $(row).find('#' + inputs[i]).val() + '",';
        }
        if (j == rows.length - 1)
            json += "}";
        else
            json += "},";

        data.push(obj);
    }
    json += "]";
    return json;
}


function saveData(tblID, fields, inputs, serviceMethod)
{
    var data = getValues(tblID, fields, inputs);
    //var data = '[{"PO_NUMBER":"a","DRUM_NUMBER":"1","C_VALUE":"2","REMARK":"3"},{"PO_NUMBER":"b","DRUM_NUMBER":"4","C_VALUE":"5","REMARK":"6"},{"PO_NUMBER":"c","DRUM_NUMBER":"7","C_VALUE":"8","REMARK":"9"}]';
    $.ajax({
        type: "POST",
        url: "http://" + window.location.host + "/Inventory/Services/" + serviceMethod,
        data: "{'data': " + data + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msg.d == true) {
                alert('Record saved successfully!!!');
                $(document).find('input[type=text], textarea').val('');
                $('select option:first-child').attr("selected", "selected");
                //window.location.reload();
            }
            else {
                alert('Error occurred while saving!!!');
            }

        }
    });
}


function saveJSonArrays(data, serviceMethod) {
    $.ajax({
        type: "POST",
        url: "http://" + window.location.host + "/Inventory/Services/Services.aspx/" + serviceMethod,
        data: "{'data': " + data + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msg.d == true) {
                alert('Record saved successfully!!!');
                $(document).find('input[type=text], textarea').val('');
                $('select option:first-child').attr("selected", "selected");
                //window.location.reload();
            }
            else {
                alert('Error occurred while saving!!!');
            }

        }
    });

}

function updateData(tblID, fields, inputs, serviceMethod, editID, editID_DBFieldName) {
    var data = getValuesForEdit(tblID, fields, inputs, editID, editID_DBFieldName);
    var urlredirect = "http://" + window.location.host + window.location.pathname;
        //var data = '[{"PO_NUMBER":"a","DRUM_NUMBER":"1","C_VALUE":"2","REMARK":"3"},{"PO_NUMBER":"b","DRUM_NUMBER":"4","C_VALUE":"5","REMARK":"6"},{"PO_NUMBER":"c","DRUM_NUMBER":"7","C_VALUE":"8","REMARK":"9"}]';
        $.ajax({
            type: "POST",
            url: "http://" + window.location.host + "/Inventory/Services/" + serviceMethod,
            data: "{'data': " + data + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg.d == true) {
                    alert('Record saved successfully!!!');
                    $(document).find('input[type=text], textarea').val('');
                    $('select option:first-child').attr("selected", "selected");
                    
                    //window.history.back(-1);
                    //updatepage();
                    top.location = urlredirect;

                }
                else {
                    alert('Error occurred while saving!!!');
                }

            }
        });
    }


